package cn.pegasus.teamwork.appinterface.session;

import javax.servlet.http.HttpSession;

import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * @author ryan.bian
 * @ClassName: MySessionContext
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2015-8-18 上午11:44:22
 */
public class MySessionContext {
	
	private static MySessionContext instance;

	/**
	 * @Fields mymap : 用来缓存一次请求中的session
	 */
	private HashMap<String, HttpSession> mymap;
	
	private MySessionContext() {
		mymap = new HashMap<String, HttpSession>();
	}

	public static MySessionContext getInstance() {
		if (instance == null) {
			instance = new MySessionContext();
		}
		return instance;
	}

	/**
	 * @param session
	 * @author Ryan.Bian
	 * @Title: AddSession
	 * @Description: 添加一个session
	 */
	public synchronized void addSession(HttpSession session) {
		if (session != null) {
			mymap.put(session.getId(), session);// 把session放入缓存
		}
	}

	/**
	 * @param session
	 * @author Ryan.Bian
	 * @Title: DelSession
	 * @Description: 删除一个session
	 */
	public synchronized void DelSession(HttpSession session) {
		if (session != null) {
			mymap.remove(session.getId());// 删除缓存的session
		}
	}

	/**
	 * @param session_id
	 * @return
	 * @author Ryan.Bian
	 * @Title: getSession
	 * @Description: 获取session
	 */
	public synchronized HttpSession getSession(String session_id) {
		if (!StringUtils.isEmpty(session_id)) {
			HttpSession session = (HttpSession) mymap.get(session_id);// 先从缓存中取
			if (session != null) {
				return session;
			}
		}

		return null;
	}
}